﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Level3X3HeartLine : MonoBehaviour
{
    public GameLevelItem gameLevelItem;
    public Button btn1;
    public Button btn2;
    public List<Level3X3HeartLineItem> itemList = new List<Level3X3HeartLineItem>();
    public Image heartImage;
    public int curIndex = 0;
    private bool isFinished = false;
    public uTools.uTweenAlpha tweenAlpha;
    void Start()
    {
        heartImage.enabled = false;
        btn1.onClick.AddListener(() =>
        {
            SoundManager.Instance.PlayAudio(SoundType.Click.ToString(), false);
            if (isFinished) return;
            Next();
        });
        btn2.onClick.AddListener(() =>
        {
            SoundManager.Instance.PlayAudio(SoundType.Click.ToString(), false);
            if (isFinished) return;
            Rot();
        });
        for (int i = 0; i < itemList.Count; i++)
        {
            itemList[i].SetRot(GetInitRotIndex(i));
        }
    }

    private void Next()
    {
        itemList[curIndex].ColorShake();
        NextIndex();
    }

    private void Rot()
    {
        itemList[curIndex].AddRot();
        NextIndex();
        CheckResult();
    }

    private void NextIndex()
    {
        curIndex++;
        if (curIndex >= itemList.Count)
            curIndex = 0;
    }

    private int GetInitRotIndex(int index)
    {
        int rotIndex = 0;
        switch (index)
        {
            case 0:
                rotIndex = 3;
                break;
            case 1:
                rotIndex = 2;
                break;
            case 2:
                rotIndex = 1;
                break;
            case 3:
                rotIndex = 3;
                break;
            case 4:
                rotIndex = 2;
                break;
            case 5:
                rotIndex = 2;
                break;
            case 6:
                rotIndex = 3;
                break;
            case 7:
                rotIndex = 2;
                break;
            default:
                rotIndex = 3;
                break;
        }

        return rotIndex;
    }

    private void CheckResult()
    {
        bool result = true;
        for (int i = 0; i < itemList.Count; i++)
        {
            if (itemList[i].rotIndex != 0)
            {
                result = false;
            }
        }
        if (result)
        {
            isFinished = true;
            heartImage.enabled = true;
            tweenAlpha.enabled = true;
            Invoke("TriggerResult", 0.35f);
        }

    }
    private void TriggerResult()
    {
        gameLevelItem.TriggerResult(true);
    }
}